package sg.edu.nus.iss.cats.action;

import javax.servlet.http.*;
import org.apache.struts.action.*;
import org.apache.struts.util.MessageResources;

import sg.edu.nus.iss.cats.form.LoginForm;
import sg.edu.nus.iss.cats.model.*;
import sg.edu.nus.iss.cats.exception.*;

import sg.edu.nus.iss.cats.controller.*;

public class LoginAction extends Action {

    
	public ActionForward execute(ActionMapping mapping,
                                 ActionForm form,
                                 HttpServletRequest request,
                                 HttpServletResponse response) {
                                    
        System.out.println("LoginAction");

        //turn our form instance into our custom form bean
        LoginForm theForm = (LoginForm) form;

        String userid = theForm.getUsername();
        String password = theForm.getPassword();
        ActionErrors errors = new ActionErrors();

        HttpSession session = request.getSession();
        
        System.out.println("Got session" + session);
        MessageResources mr=(MessageResources)request.getAttribute(Action.MESSAGES_KEY);
        System.out.println("MessageResource="+mr.getMessage("title.login"));
        
        try {
            if (userid == null || password == null)
                throw new NoLoginException("User not logged in");

            //Validate the password and create a userSession with key userid
            UserSessionManager sessionMgr = new UserSessionManager();
            
            System.out.println("Going to validate");
            UserSession userSession = sessionMgr.validate(userid, password);

            session.setAttribute("USERSESSION", userSession);

            User user = userSession.getUser();
            
            System.out.println("LoginAction: Getting roles");
            
            Role[] roles = user.getRoles();
            
            for (int i=0;i<roles.length;i++){
                System.out.println("Role " + i + " : " + roles[i].getName());           
             }
                
            
            
            //Set Employee info in session
            if (userSession.getEmployee() != null) {

                if (user.hasRole("manager"))
                    return mapping.findForward("managerDefault");
                else
                    return mapping.findForward("employeeDefault");

            } else {
                return mapping.findForward("adminDefault"); //admin
            }
        } catch (NoLoginException e) {
            //return an ActionForward respresenting the logical failure page
            // Report any errors we have discovered back to the original form
            return mapping.findForward("failure");
        }catch (WrongPasswordException e) {
            errors.add(
            		"soehanwin.error",
                new ActionError("error.password.mismatch","soehanwin error wrong password"));
            // Report any errors we have discovered back to the original form
            saveErrors(request, errors);
            return mapping.findForward("failure");
        }catch (UserNotFoundException e) {
            //If user not found in DB - say user account not found
            errors.add(
                ActionErrors.GLOBAL_ERROR,
                new ActionError("error.password.mismatch","soehanwin error"));
            // Report any errors we have discovered back to the original form
            saveErrors(request, errors);
            return mapping.findForward("failure");
        } catch (Exception e) {
            //return an ActionForward respresenting the logical failure page
            errors.add(
                ActionErrors.GLOBAL_ERROR,
                new ActionError("error.password.mismatch","soehanwin error"));
            // Report any errors we have discovered back to the original form
            saveErrors(request, errors);
            servlet.log(
                "LoginAction: Employee '"
                    + userid
                    + "' could not log on in session "
                    + e,
                0);
            return mapping.findForward("failure");
        }
        
        
    }
}